CODE 63. Sqrt(x)

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/06/2013-10-06-CODE 63 Sqrt(x)/

访问原文「CODE 63. Sqrt(x)

Implement int sqrt(int x).
Compute and return the square root of x.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int sqrt(int x) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (x <= 0) {
return 0;
}
double pre = -1.0;
double cur = 1.0;
while (Math.abs(pre - cur) > 0.00001) {
pre = cur;
cur = (cur + x / cur) / 2;
}
return (int) cur;
}
Jerky Lu wechat
欢迎加入微信公众号